import { Component } from "react";
import { Select } from "antd";
// propTypes
import PropTypes from "prop-types";
import { custom } from "@/api/common.js";

const { Option } = Select;

class SelectComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      options: [],
      value: null
    };
  }
  static getDerivedStateFromProps(props, state) {
    const { value, propsKey } = props;
    const { options } = state;
    if (!isNaN(value) && value && options.length > 0) {
      const data = options.filter(item => +item[propsKey.value] === +value)[0];
      const name = data && data[propsKey.label];
      return {
        value: name
      };
    }
    return null;
  }
  componentDidMount() {
    const { url } = this.props;
    this.getData(url);
  }
  getData = async url => {
    const res = await custom({ url, data: {} });
    if (res.data && res.data.data.length > 0) {
      this.setState({ options: res.data.data });
    }
  };
  onCurrencyChange = val => {
    // 这个onchange是form.item传下来的
    if (Number.isNaN(parseInt(val))) return;

    //自定义表单--拿到里面的值-传个submit按钮提交时里面获取的值
    this.props.onChange(parseInt(val));
  };

  render() {
    const { options, value } = this.state;
    const { style, placeholder, propsKey } = this.props;
    return (
      // 这里用到了自定义表单，因为把表单单独抽离出来 form无法校验到所以需要进行处理 关键value onChange 根据文档需要绑定的
      <Select
        style={style}
        placeholder={placeholder}
        onChange={this.onCurrencyChange}
        value={value}
      >
        {options &&
          options.map(elem => {
            return (
              <Option key={elem[propsKey.value]} value={elem[propsKey.value]}>
                {elem[propsKey.label]}
              </Option>
            );
          })}
      </Select>
    );
  }
}

// 校验数据类型
SelectComp.propTypes = {
  url: PropTypes.string, //必须要的 要么就和options二选一
  options: PropTypes.array,
  propsKey: PropTypes.object, //里面的数据结构是 value label   propsKey:{label:'name',value:'id'} 用来获取值 配合url一起使用
  style: PropTypes.object,
  placeholder: PropTypes.string
};
// 默认
SelectComp.defaultProps = {
  options: [],
  style: {},
  url: "",
  placeholder: "请选择"
};
export default SelectComp;
